<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Heartbeat Example</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      margin-top: 50px;
    }

    button {
      margin: 10px;
      padding: 10px 20px;
      font-size: 16px;
    }
  </style>
</head>

<body>
  <h1>Heartbeat Example</h1>
  <button id="startButton">启动心跳</button>
  <button id="stopButton">停止心跳</button>
  <p id="status">心跳未启动</p>

  <script>
    class Heartbeat {
      constructor() {
        this.heartbeatTimer = null; // 用于存储 setInterval 的定时器 ID
        this.heartbeatTimeoutTimer = null; // 用于存储 setTimeout 的定时器 ID
      }

      startHeartbeat () {
        // 每隔5秒发送一次心跳
        this.heartbeatTimer = setInterval(() => {
          console.log("发送心跳...");
          document.getElementById("status").innerText = "心跳中...";
        }, 5000);

        // 10秒后停止心跳
        this.heartbeatTimeoutTimer = setTimeout(() => {
          console.log("停止心跳...");
          clearInterval(this.heartbeatTimer); // 清除 setInterval 定时器
          document.getElementById("status").innerText = "心跳已停止（自动）";
        }, 10000);
      }

      stopHeartbeat () {
        // 清除 setInterval 定时器
        clearInterval(this.heartbeatTimer);
        // 清除 setTimeout 定时器
        clearTimeout(this.heartbeatTimeoutTimer);
        console.log("心跳已停止");
        document.getElementById("status").innerText = "心跳已停止（手动）";
      }
    }

    // 创建 Heartbeat 实例
    const heartbeat = new Heartbeat();

    // 获取按钮元素
    const startButton = document.getElementById("startButton");
    const stopButton = document.getElementById("stopButton");

    // 绑定按钮事件
    startButton.addEventListener("click", () => {
      heartbeat.startHeartbeat();
      document.getElementById("status").innerText = "心跳已启动";
    });

    stopButton.addEventListener("click", () => {
      heartbeat.stopHeartbeat();
    });
  </script>
</body>

</html>